package com.ruoyi.qywx.getway.api;

import cn.hutool.json.JSONUtil;
import com.ruoyi.common.constant.ErrorConstants;
import com.ruoyi.common.core.cache.Meta;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.StrUtils;
import com.ruoyi.qywx.getway.dto.QyExtContactDto;
import com.ruoyi.qywx.getway.request.TxRequest;
import com.ruoyi.qywx.getway.request.TxResponse;
import com.ruoyi.qywx.model.vo.CustomerFollowerVo;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author : hcl
 * @Date : 2023/8/22 16:15
 * 客户管理API
 */
@Slf4j
public class ExternalcontactApi {
    /**
     * 客户详情
     * https://developer.work.weixin.qq.com/document/path/92265
     *
     * @param extUserId 外部联系人id
     * @param cursor    游标
     */
    public static QyExtContactDto externalcontactGet(Meta meta, String extUserId, String cursor) {
        Map<String, String> params = new HashMap<>();
        params.put("external_userid", extUserId);
        if (StrUtils.isNotEmpty(cursor)) {
            params.put("cursor", cursor);
        }
        TxResponse response = TxRequest.getInstance(meta.getCorpid(), meta.getAppSecret())
                .get("/cgi-bin/externalcontact/get", params);
        if (!response.isSuccess()) {
            log.error("获取客户详情失败,extUserId={}", extUserId);
            return null;
        }
        return response.getJson().toBean(QyExtContactDto.class);
    }

    /**
     * https://developer.work.weixin.qq.com/document/path/92115
     */
    public static boolean editExternalContactRemark(Meta meta, CustomerFollowerVo vo) {
        if (StrUtils.isEmpty(vo.getExtUserId()) && StrUtils.isEmpty(vo.getUserId())) {
            throw new ServiceException(ErrorConstants.PARAMS_ERR);
        }
        Map<String, Object> params = new HashMap<>();
        if (StrUtils.isNotEmpty(vo.getRemark())) {
            params.put("remark", vo.getRemark());
        }
        if (Objects.nonNull(vo.getDescription())) {
            params.put("description", vo.getDescription());
        }
        if (Objects.nonNull(vo.getDescription())) {
            params.put("remark_company", vo.getRemarkCorpName());
        }
        if (StrUtils.isNotEmpty(vo.getRemarkMobiles())) {
            params.put("remark_mobiles", CollectionUtils.toStrList(vo.getRemarkMobiles()));
        }
        params.put("userid", vo.getUserId());
        params.put("external_userid", vo.getExtUserId());
        String values = JSONUtil.toJsonStr(params);
        TxResponse response = TxRequest.getInstance(meta.getCorpid(), meta.getAppSecret())
                .post("/cgi-bin/externalcontact/remark", values);
        if (response.isSuccess()) return true;
        String err = response.getError();
        log.error("更新用户备注信息失败:{} === {}", values, err);
        throw new ServiceException("更新用户备注信息失败:" + err);
    }
}
